package com.example.mq.common;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-08-29
 * Time: 11:11
 */

import java.io.*;

/**
 * 序列化操作
 */
public class BinaryTool {
    //把一个对象序列化成一个字节数组
    public static byte[] toBytes(Object object) throws IOException {
        //这个流对象相当于一个变长数组
        //可以把object序列化的数据逐渐写到 byteArrayOutputStream中,最后统一转成byte[]数组
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                //此处的writeObject就会把该对象序列化,生成的二进制字节数据,就会写入到
                //ObjectOutputStream中
                //但是OutPutStream又关联到了ByteArrayOutputStream,所以最后就写入到byteArrayOutputStream
                objectOutputStream.writeObject(object);

            }
            //这个操作就是把 byteArrayOutputStream中持有的已经序列化过的二进制数据取出来变成byte[]数组
            return byteArrayOutputStream.toByteArray();
        }
    }

    //把一个字节数组反序列化成一个对象
    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                //此处的readObject,就是从data这个数组读取数据并进行反序列化
                object = objectInputStream.readObject();

            }
        }
        return object;
    }
}



